﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

namespace GetEmailAddress
{

    class SqlHelper
    {
        public readonly string CookieStr;

       


        #region otherMethods

        public SqlHelper()
        {
            CookieStr = GetCookieStr();
        }

        public static bool SqlHelperData(List<Info> sqls)
        {
            using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;User ID=sa;Password=Password01!"))
            {
                con.Open();
                SqlTransaction trans = con.BeginTransaction();
                SqlCommand command = con.CreateCommand();
                command.Transaction = trans;
                command.Connection = con;
                try
                {
                    foreach (var sql in sqls)
                    {
                        command.CommandText = string.Format(@"insert into EmailAddress(userID, emailAddress) values({0},'{1}')", sql.UserID, sql.EmailAddress);

                        int i = command.ExecuteNonQuery();

                    }
                    trans.Commit();

                }
                catch (Exception e)
                {
                    trans.Rollback();
                    Console.Write(e.Message);

                }
            }
            return true;
        }


        private string GetStatus(string info)
        {

            int checkInt =
            info.ToLower().IndexOf("check");
            int coop = info.ToLower().IndexOf("合作中");
            if (checkInt < coop)
                return "合作中";
            else return "取消合作";

        }
        public bool InsertInfo(List<string[]> list)
        {

            using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;User ID=sa;Password=Password01!"))
            {
                con.Open();
                SqlTransaction trans = con.BeginTransaction();
                SqlCommand command = con.CreateCommand();
                command.Transaction = trans;
                command.Connection = con;
                try
                {
                    foreach (var sql in list)
                    {
                        command.CommandText = string.Format(@"INSERT INTO [Form]
           ([NO.]
           ,[Name]
           ,[Slogan]
           ,[Address]
           ,[People]
           ,[Tel]
           ,[QQ]
           ,[Cor]
           ,[Status]
           ,[From]
           ,[Source],[Index])
     VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')",
           sql[0], sql[1], sql[2], sql[4], sql[5], sql[6], sql[7], sql[8], GetStatus(sql[11]), sql[14], sql[15], sql[16]);

                        int i = command.ExecuteNonQuery();

                    }
                    trans.Commit();

                }
                catch (Exception e)
                {
                    trans.Rollback();
                    Console.Write(e.Message);

                }
            }
            return true;
        }

        public void WriteToData(Obj o)
        {

            string url =
             "http://50.97.89.133:8080/MailViewAction.do?order_sn=Fen2013012813158861&op_user_id={1}&user_id={0}&order_id=2002640";
            List<Info> list;

            Stack<Info> stackInfo = new Stack<Info>();

            for (int i = o.StartIndex; i <= o.EndIndex; i++)
            {
                string tempUrl = string.Format(url, i, o.UserID);
                Console.Write("  " + i);
                stackInfo.Push(new Info() { UserID = i, EmailAddress = GetEmail(tempUrl) });
                if (stackInfo.Count == 100)
                {
                    list = new List<Info>();
                    while (stackInfo.Count > 0)
                    {
                        list.Add(stackInfo.Pop());
                    }
                    SqlHelper.SqlHelperData(list);
                }
            }
        }

        private string GetEmail(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "Get";
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            string en = response.CharacterSet;

            Encoding encoding = Encoding.GetEncoding(en);
            using (Stream getStream = response.GetResponseStream())
            {


                //若response.ContentEncoding 的值为gzip 则需进行 解压缩
                using (GZipStream gzip = new GZipStream(getStream, CompressionMode.Decompress))
                {
                    using (MemoryStream msTemp = new MemoryStream())
                    {
                        int count = 0;
                        byte[] buf = new byte[100];
                        while ((count = gzip.Read(buf, 0, buf.Length)) > 0)
                        {
                            msTemp.Write(buf, 0, count);
                        }
                        msTemp.Position = 0;

                        using (StreamReader sr = new StreamReader(msTemp, encoding))
                        {


                            string html = sr.ReadToEnd();

                            int index = html.IndexOf("receiverMail", 4000);
                            html = html.Substring(index);
                            index = html.IndexOf("=\"") + 2;
                            int lastIndex = html.IndexOf("\"/");

                            string emailAddress = html.Substring(index, lastIndex - index);
                            return emailAddress;
                        }
                    }
                }
            }
        }



        public void WriteForm(Obj o)
        {
            string url =
            "http://houtai.wholesale-inc.com/index.php/SupplierMaintainAction/suppInfo/4180";

            url = "http://houtai.wholesale-inc.com/index.php/SupplierMaintainAction/suppInfo/{0}";

            // var a = GetEmail(url);
            List<string[]> queryInfo = new List<string[]>();
            for (int i = o.StartIndex; i <= o.EndIndex; i++)
            {
                Console.Write(i + "  ");
                string tempURL = string.Format(url, i);
                queryInfo.Add(GetResponsetInfo(tempURL, i));
                if (queryInfo.Count == 10 || i == o.EndIndex)
                {
                    InsertInfo(queryInfo);
                    queryInfo = new List<string[]>();
                }
            }

        }
        #endregion


        #region userfullInfo


        private string[] GetResponsetInfo(string url, int id)
        {
            HttpWebRequest request;
            HttpWebResponse response;
            string cookieStr;
            cookieStr = CookieStr;
            string[] infos = new string[17];
            infos[16] = id.ToString();

            request = WebRequest.Create(url) as HttpWebRequest;
            request.Proxy = GetProx();
            request.Method = "Get";
            request.Headers.Add("Cookie", cookieStr);
            response = request.GetResponse() as HttpWebResponse;

            string en = response.CharacterSet;

            Encoding encoding = Encoding.GetEncoding(en);
            var contentEncoding = response.ContentEncoding;


            using (Stream getStream = response.GetResponseStream())
            {
                using (StreamReader sr = new StreamReader(getStream, encoding))
                {


                    string html = sr.ReadToEnd();

                    string searchStr = "width=\"83%\"";

                    MatchCollection matches = Regex.Matches(html, searchStr);

                    var index = 0;


                    foreach (Match match in matches)
                    {

                        int startIndex = match.Index + 12;
                        int tdIndex = html.IndexOf("</td>", match.Index);
                        int length = tdIndex - startIndex;
                        infos[index] =
                           html.Substring(match.Index + 12, length);
                        index++;
                    }

                }
            }
            return infos;
        }



        /// <summary>
        /// 运用post 方式进行登录，获取cookie 值，然后访问其他位置
        /// </summary>
        /// <returns></returns>
        private static string GetCookieStr()
        {
            string postData = "loginusername=杨斐&loginpassword=yangfei123";
            Encoding utfEncoding = Encoding.GetEncoding("UTF-8");
            byte[] data = utfEncoding.GetBytes(postData);
            CookieContainer cookieCon = new CookieContainer();

            HttpWebRequest request = WebRequest.Create("http://houtai.wholesale-inc.com/index.php/EntranceAction/login") as HttpWebRequest;

            var prox = GetProx();

            request.Method = "Post";
            request.Proxy = prox;
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            request.CookieContainer = cookieCon;
            //request.UserAgent =
            //    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(data, 0, data.Length);
            }

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            string cookieStr = request.CookieContainer.GetCookieHeader(request.RequestUri);
            return cookieStr;
        }

        private static WebProxy GetProx()
        {
            WebProxy prox = new WebProxy("135.251.33.16", 8080);
            prox.Credentials = new NetworkCredential("hwenlong", "Password00!", "ad4");
            //  request.Proxy = prox;
            return prox;
        }

        #endregion
    }
}


